﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using APH.Parl2.Shared.Contracts;
using APH.Parl2.Data.DataAccess.Publishing;
using System.IO;
using System.Xml.Linq;
using System.Xml;
using System.ServiceModel;

namespace APH.Parl2.Services.SearchIngest
{
    public class SearchIngestionService : ISearchIngestionService, IPublishEvents
    {
        [OperationBehavior(TransactionScopeRequired = true)]
        public void OnPublished(Guid documentId)
        {
            IngestDocument(documentId);
        }

        public void IngestDocument(Guid documentId)
        {
            Console.WriteLine("Ingesting Document: {0}", documentId);

            var writeDoc = WriteHelper.GetDocumentById(documentId);
            var xDoc = XDocument.Parse(writeDoc.Data);
            XNamespace db = "http://docbook.org/ns/docbook";

            var info = xDoc.Element(db + "article").Element(db + "info");
            var authorPersonName = info.Element(db + "author").Element(db + "personname");

            string author = (string)authorPersonName.Element(db + "firstname") + " " + (string)authorPersonName.Element(db + "surname");
            string title = (string) info.Element(db + "title");

            ReadHelper.CreateDocument(author, writeDoc.Data, title);
        }
    }
}
